#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/2/26 12:55
# @Author  : leon yan
# @Site    : 
# @File    : qCreateQRCode.py
# @Software: PyCharm

import os
from PIL import Image
from PyQt5.QtCore import QObject, QDir

import pyzbar
import qrcode


class QCreateQRCode(QObject):
    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)

    def do_QRCode(self, QRCodeText, QRParameter):
        pass
        curPath = QDir.currentPath()  # 获取系统当前目录
        savePath = curPath + "/.temp/QRCode.jpg"
        '''读内容'''
        code_Data = QRCodeText
        # '''生成带中心图片的二维码'''
        # self.make_qr_code_with_icon(
        #     code_Data, "QRcodeCenter.jpg", "qrcode.png")  # 内容，center图片，生成二维码图片

        '''生成没有中心图片的二维码'''
        self.make_qr_code(code_Data, savePath, QRParameter[0], QRParameter[1], QRParameter[2], QRParameter[3])

        if not os.path.exists(savePath):
            raise FileExistsError(savePath)
            return
        return savePath

        '''图片已保存，名称为：QRCode.jpg"'''
        # results = self.decode_qr_code(savePath)

        '''正在解码'''
        # if len(results):
        #     print("解码结果是：")
        #     print(results[0].data.decode("utf-8"))
        # else:
        #     print("Can not recognize.")

    '''
    ====================================
    test2:生成二维码保存及对二维码解码输出
    ====================================
    '''

    def make_qr_code(self, content, save_path=None, *args):
        if args[0] <= 0:
            sversion = 4
        else:
            sversion = args[0]
        if args[1] <= 0 or args[1] > 40:
            sSize = 8
        else:
            sSize = args[1]
        if args[2] == 0:
            sCorrect = qrcode.constants.ERROR_CORRECT_M
        elif args[2] == 1:
            sCorrect = qrcode.constants.ERROR_CORRECT_L
        elif args[2] == 2:
            sCorrect = qrcode.constants.ERROR_CORRECT_Q
        elif args[2] == 3:
            sCorrect = qrcode.constants.ERROR_CORRECT_H

        qr_code_maker = qrcode.QRCode(version=sversion,
                                      error_correction=sCorrect,
                                      box_size=sSize,
                                      border=1,
                                      )
        qr_code_maker.add_data(data=content)
        qr_code_maker.make(fit=True)
        img = qr_code_maker.make_image(fill_color="black", back_color="white")
        if args[3] == "label":
            newimg = img.resize(
                (100, 100), Image.ANTIALIAS)
        else:
            newimg = img.resize(
                (260, 260), Image.ANTIALIAS)
        if save_path:
            newimg.save(save_path)
        else:
            newimg.show()  # 显示二维码图片

        '''可输出到终端显示'''
        # qr_code_maker.print_ascii(invert=True)

    def make_qr_code_with_icon(self, content, icon_path, save_path=None, *args):
        if not os.path.exists(icon_path):
            raise FileExistsError(icon_path)

        # First, generate an usual QR Code image
        qr_code_maker = qrcode.QRCode(version=5,
                                      error_correction=qrcode.constants.ERROR_CORRECT_H,
                                      box_size=8,
                                      border=4,
                                      )
        qr_code_maker.add_data(data=content)
        qr_code_maker.make(fit=True)
        qr_code_img = qr_code_maker.make_image(
            fill_color="black", back_color="white").convert('RGBA')

        # Second, load icon image and resize it
        icon_img = Image.open(icon_path)
        code_width, code_height = qr_code_img.size
        icon_img = icon_img.resize(
            (code_width // 4, code_height // 4), Image.ANTIALIAS)

        # Last, add the icon to original QR Code
        qr_code_img.paste(icon_img, (code_width * 3 // 8, code_width * 3 // 8))

        if save_path:
            qr_code_img.save(save_path, "jpg")  # 保存二维码图片
            qr_code_img.show()  # 显示二维码图片
        else:
            print("save error!")

    def decode_qr_code(self, code_img_path):
        if not os.path.exists(code_img_path):
            raise FileExistsError(code_img_path)
            return

        # Here, set only recognize QR Code and ignore other type of code
        return pyzbar.decode(Image.open(code_img_path), symbols=[pyzbar.ZBarSymbol.QRCODE])
